package com.example.qrmenu;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBHandler extends SQLiteOpenHelper {

	private static final int DATABASE_VERSION=1;
	private static final String DATABASE_NAME="QRMenu";
	private static final String UserTable="User";
	
	private static final String userName="name";
	private static final String accessToken="accessToken";
	Context context;
	public DBHandler(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
		this.context=context;
	}

	@Override
	//FIXME add check here to see if the database and table exists, if true then do not create db or table
	public void onCreate(SQLiteDatabase db) {
		Log.i("rohit","creating database and table");
		 String CREATE_CONTACTS_TABLE = "CREATE TABLE " + UserTable + "("
	                + userName + " STRING PRIMARY KEY," + accessToken + " TEXT"+ ")";
	        db.execSQL(CREATE_CONTACTS_TABLE);
	}

	private boolean checkDatabase() {
		 SQLiteDatabase checkDB = null;
		    try {
		        checkDB = SQLiteDatabase.openDatabase(context.getDatabasePath(DATABASE_NAME).toString(), null,
		                SQLiteDatabase.OPEN_READONLY);
		        checkDB.close();
		    } catch (SQLiteException e) {
		    	Log.d("rohit", "data base does not exist");
		       return false;
		    }
		    return checkDB != null ? true : false;
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
        db.execSQL("DROP TABLE IF EXISTS " + UserTable);
        onCreate(db);
	}

	public void addUser(UserStatusInfo user) {
	    SQLiteDatabase db = this.getWritableDatabase();
	 
	    ContentValues values = new ContentValues();
	    values.put(userName, user.getUsername()); // Contact Name
	    values.put(accessToken, user.getAccessToken()); // Contact Phone Number
	 
	    // Inserting Row
	    db.insert(UserTable, null, values);
	    db.close(); // Closing database connection
	}
	
	//FIXME call this method first and check to see if there are any rows in the table if there are no rows then insertrow
	public UserStatusInfo getUser(String user) {
	    SQLiteDatabase db = this.getReadableDatabase();
	 
	    Cursor cursor = db.query(UserTable, new String[] { userName,
	            accessToken}, userName + "=?",
	            new String[] { user }, null, null, null, null);
	    if (cursor != null)
	        cursor.moveToFirst();
	 
	    UserStatusInfo userR = new UserStatusInfo(cursor.getString(0),
	            cursor.getString(1));
	    // return contact
	    return userR;
	}
	//FIXME this will be called when the accesToken does not work and the access token recored needs to be updated
	public int updateUser(UserStatusInfo user) {
		SQLiteDatabase db = this.getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put(userName, user.getUsername());
		values.put(accessToken, user.getAccessToken());
		return db.update(UserTable, values, userName + " = ?",new String[] { String.valueOf(user.getUsername()) });
		}
	
	 public void deleteUser(UserStatusInfo user) {
	        SQLiteDatabase db = this.getWritableDatabase();
	        db.delete(UserTable, userName + " = ?",
	                new String[] { String.valueOf(user.getUsername()) });
	        db.close();
	    }
	 
	// Getting All Contacts
	    public List<UserStatusInfo> getAllUsers() {
	        List<UserStatusInfo> userList = new ArrayList<UserStatusInfo>();
	        // Select All Query
	        boolean flag = isTableExists(UserTable);
	        Log.i("rohit :"," checkDataBase return value is "+ flag);
	        
	        if(flag){
	        	String selectQuery = "SELECT  * FROM " + UserTable;		 
	  	        SQLiteDatabase db = this.getWritableDatabase();
	  	        Cursor cursor = db.rawQuery(selectQuery, null);
	  	 	  	        // looping through all rows and adding to list
	  	        if (cursor.moveToFirst()) {
	  	            do {
	  	                UserStatusInfo userData = new UserStatusInfo();
	  	                userData.setUsername(cursor.getString(0));
	  	                userData.setAccessToken(cursor.getString(1));
	  	                userList.add(userData);
	  	            } while (cursor.moveToNext());
	  	        }
	        } else {
	        	 String CREATE_CONTACTS_TABLE = "CREATE TABLE " + UserTable + "("
	 	                + userName + " STRING PRIMARY KEY," + accessToken + " TEXT"+ ")";
	 	        this.getReadableDatabase().execSQL(CREATE_CONTACTS_TABLE);
	        	return null;
	        }
	      
	        return userList;
	    }
	    
	    public boolean isTableExists(String tableName) {
			Cursor cursor = this.getReadableDatabase().rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name = '"+tableName+"'", null);
	        if(cursor!=null) {
	            if(cursor.getCount()>0) {
	                                cursor.close();
	                return true;
	            }
	                        cursor.close();
	        }
	        return false;
	    }
	 
}
